package cn.codeant.aircrack.utils;

import android.content.Context;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


/**
 * Description: assets目录下不存在空文件夹，即使工程中有空文件夹，生成apk后也会丢弃
 * Created by Codeant on 2019/5/17.
 */
public class AssetUtils {
    public static boolean copyFile(Context context,String src,String dest,boolean overwrite){
        InputStream is = null;
        OutputStream os = null;

        File destFile = new File(dest);
        File dir = destFile.getParentFile();
        if(!dir.exists())
            dir.mkdirs();
        if(destFile.exists()&&(!overwrite)){
            return true;
        }
        destFile.delete();

        try {
            is = context.getAssets().open(src);
            os = new FileOutputStream(destFile);
            byte[] buf = new byte[1024];
            int len;
            while ((len=is.read(buf))>0)
                os.write(buf,0,len);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }finally {
            try{
                if(null!=is)
                    is.close();
            }catch (Exception ignored){}
            try{
                if(null!=os)
                    os.close();
            }catch (Exception ignored){}
        }

        return true;
    }

    public static boolean copyFile(Context context,String src,String dest){
        return copyFile(context,src,dest,false);
    }

    public static boolean copyFileOverwrite(Context context,String src,String dest){
        return copyFile(context,src,dest,true);
    }


    public static boolean copyDir(Context context,String src,String dest,boolean overwrite){
        try {
            String[] fileList = context.getAssets().list(src);
            if(null==fileList) {
                return false;
            }

            if(fileList.length>0){
                // 当前是文件夹
                File destDir = new File(dest);
                destDir.mkdirs();
                for(String fileName:fileList){
                    if(!copyDir(context,src+File.separator+fileName,dest+File.separator+fileName,overwrite)){
                        return false;
                    }
                }
                return true;
            }else{
                // 当前是文件(assets下的空文件夹获取不到，apk包中也不会有空文件夹)
                return copyFile(context,src,dest,overwrite);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static boolean copyDir(Context context,String src,String dest){
        return copyDir(context,src,dest,false);
    }

    public static boolean copyDirOverwrite(Context context,String src,String dest){
        return copyDir(context,src,dest,true);
    }
}
